package com.itzmn.java.javase.io.bio;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/26 14:03
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description:  socket编程，bio
 */
public class BIOServer {

    private int port;
    private ServerSocket serverSocket = null;

    public BIOServer(){
        this(8080);
    }

    public BIOServer(int port){
        this.port = port;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务器启动成功，port:"+this.port);
        } catch (IOException e) {
            System.out.println("服务器启动失败...");
            e.printStackTrace();
        }
    }

    /**
     * 处理客户端连接的业务
     */
    private void listen(){
        InputStream inputStream = null;
        try {
            while (true){
                System.out.println("阻塞，等待客户端连接..."+System.currentTimeMillis());
                Socket socket = serverSocket.accept();
                System.out.println("有客户端连接了...."+System.currentTimeMillis());
                inputStream = socket.getInputStream();
                int len = 0;
                while (true){
                    while (len == 0){
                        len = inputStream.available();
                    }
                    System.out.println(len);
                    byte[] bytes = new byte[len];
                    inputStream.read(bytes);
                    System.out.println("客户端说:"+new String(bytes));
                    len = 0;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new BIOServer().listen();
    }

}
